<script setup>

import {
  crmLeadsTransformAPI,
  crmLeadsDeleteAPI
} from '/src/api/crm/leads.js'
import {
  crmCustomerLockAPI,
  crmCustomerDeleteAPI,
  crmCustomerPoolDeleteAPI,
  crmCustomerReceiveAPI
} from '/src/api/crm/customer.js'
import {crmContactsDeleteAPI} from '/src/api/crm/contacts.js'
import {crmBusinessDeleteAPI} from '/src/api/crm/business.js'
import {
  crmContractDeleteAPI,
  crmContractCancelAPI
} from '/src/api/crm/contract.js'
import {crmReceivablesDeleteAPI} from '/src/api/crm/receivables.js'
import {crmReceivablesPlanDeleteAPI} from '/src/api/crm/receivablesPlan.js'
import {crmReturnVisitDeleteAPI} from '/src/api/crm/visit.js'
import {
  crmProductStatusAPI,
  crmProductDeleteAPI
} from '/src/api/crm/product.js'
import {crmInvoiceDeleteIdsAPI} from '/src/api/crm/invoice.js'
import TransferHandle from '/src/views/crm/componentsNew/SelectionHandle/TransferHandle.vue' // 转移
import AllocHandle from '/src/views/crm/componentsNew/SelectionHandle/AllocHandle.vue' // 公海分配操作
import DealStatusHandle from '/src/views/crm/componentsNew/SelectionHandle/DealStatusHandle.vue' // 客户状态修改操作
import PutPoolHandle from '/src/views/crm/componentsNew/SelectionHandle/PutPoolHandle.vue'
import {getCurrentInstance, reactive, ref, computed, watch, onMounted} from "vue"
import {ElMessageBox, ElMessage} from "element-plus"
import {useErpUserStore} from "/src/store/modules/usererp.js";
import {crmOptionKey} from "/src/views/crm/componentsNew/SzCrud/keys.js";


defineOptions({
  name: 'SzDetailHead',
})

const properties = defineProps({
  /** 模块ID */
  id: [String, Number],
  /** 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息 合同作废需要合同状态*/
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 详情的头部
  detailHead: {
    type: Array,
    default: () => {
      return []
    }
  },
  // 所有可切换的列表数据，即分页查询回来的10条数据
  pageList: Array
})

const emits = defineEmits(['pageChange', 'handle', 'handle-click'])

const detailHeadOption = reactive({
  crmType: "customer",
  isSeas: false
})

const moreTypes = ref([]) // 更多操作

const handleDialogShow = reactive({
  transferDialogShow: false, // 转移操作
  allocDialogShow: false, // 公海分配操作提示框
  dealStatusShow: false, // 成交状态修改框
  putPoolShow: false // 客户放入公海
})


const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})


const crmIcon = computed(() => {
  return `/src/assets/img/crm/${detailHeadOption.crmType}.png`
})
const typeName = computed(() => {
  return ({
        leads: '线索',
        customer: '客户',
        contacts: '联系人',
        product: '产品',
        business: '商机',
        contract: '合同',
        receivables: '回款',
        receivablesPlan: '回款计划',
        visit: '回访',
        invoice: '发票'
      }[detailHeadOption.crmType] || ''
  )
})

const name = computed(() => {
  if (detailHeadOption.crmType === 'receivables') {
    return properties.detail.number
  } else if (detailHeadOption.crmType === 'customer') {
    return properties.detail.customerName
  } else if (detailHeadOption.crmType === 'business') {
    return properties.detail.businessName
  } else if (detailHeadOption.crmType === 'visit') {
    return properties.detail.visitNumber
  } else if (detailHeadOption.crmType === 'invoice') {
    return properties.detail.invoiceApplyNumber
  } else if (detailHeadOption.crmType === 'receivablesPlan') {
    return properties.detail.num
  }
  return properties.detail.name
})
// 展示转移
const showTransfer = computed(() => {
  if (
      detailHeadOption.crmType === 'customer' ||
      detailHeadOption.crmType === 'visit' ||
      detailHeadOption.isSeas
  ) {
    return false
  }

  if (detailHeadOption.crmType === 'contract') {
    return (
        properties.detail &&
        properties.detail.checkStatus != 8 &&
        crm.value[detailHeadOption.crmType].transfer
    )
  }

  return crm.value[detailHeadOption.crmType].transfer
})

const showEdit = computed(() => {
  //  8 已作废 的合同可以编辑
  return detailHeadOption.isSeas ? false : crm.value[detailHeadOption.crmType].update
})

// 展示领取
const showGet = computed(() => {
  return detailHeadOption.isSeas && whetherTypeShowByPermission('get')
})

// 展示分配
const showAlloc = computed(() => {
  return detailHeadOption.isSeas && whetherTypeShowByPermission('alloc')
})


/**
 * 客户是否锁定
 */
const isLock = computed(() => {
  if (properties.detail) {
    return properties.detail.status == 2 // 1是正常 2 是锁定
  }
  return false
})

/**
 * 展示成交按钮
 */
const showDealStatus = computed(() => {
  return (
      !detailHeadOption.isSeas &&
      detailHeadOption.crmType == 'customer' &&
      crm.value[detailHeadOption.crmType].dealStatus
  )
})

/**
 * 权限内的更多按钮
 */
const permissionMoreTypes = computed(() => {
  return moreTypes.value.filter(item => {
    return whetherTypeShowByPermission(item.type)
  })
})

// watch(() => crmOption.isSeas, () => {
//   moreTypes.value = getSelectionHandleItemsInfo()
// })

onMounted(() => {
  moreTypes.value = getSelectionHandleItemsInfo()
  console.log("moreTypes", moreTypes)
})


/** 更多操作 */
function handleTypeClick(type) {
  if (type == 'edit') {
    // 编辑
    emits('handle', {type: 'edit'})
  } else if (type == 'transfer') {
    // 转移
    handleDialogShow.transferDialogShow = true
  } else if (
      type == 'transform' ||
      type == 'delete' ||
      type == 'lock' ||
      type == 'unlock' ||
      type == 'start' ||
      type == 'disable' ||
      type == 'get' ||
      type == 'cancel'
  ) {
    let message = ''
    if (type == 'transform') {
      message = '确定将这些线索转换为客户吗?'
    } else if (type == 'delete') {
      message = detailHeadOption.isSeas ? '若客户下有联系人，联系人将一并删除。确定删除？' : '确定删除?'
    } else if (type == 'lock') {
      message = '确定要锁定该客户吗？锁定后将不会掉入公海。'
    } else if (type == 'unlock') {
      message = '确定要解锁该客户吗？'
    } else if (type == 'start') {
      message = '确定要上架该产品吗?'
    } else if (type == 'disable') {
      message = '确定要下架该产品吗?'
    } else if (type == 'get') {
      message = '确定要领取该客户吗?'
    } else if (type == 'cancel') {
      message = '确定要作废此合同吗?'
      if (properties.detail.receivablesCount) {
        message = '合同下有相关回款,确定要作废吗?'
      }
    }

    ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      confirmHandle(type)
    }).catch(() => {
    })
  } else if (type == 'alloc') {
    // 公海分配操作
    handleDialogShow.allocDialogShow = true
  } else if (type == 'deal_status') {
    // 客户成交状态操作
    handleDialogShow.dealStatusShow = true
  } else if (type == 'put_seas') {
    // 客户放入公海
    handleDialogShow.putPoolShow = true
  } else if (type == 'print') {
    // 打印
    const id = properties.detail[`${detailHeadOption.crmType}Id`]
    // const routeData = this.$router.resolve(`/print/?module=${props.crmType}&id=${id}`)
    const routeData = $router.resolve(`/print/?module=${detailHeadOption.crmType}&id=${id}`)
    window.open(routeData.href, '_blank')
  } else if (type == 'copyContract') {
    emits('handle-click', {type})
  }
}

function confirmHandle(type) {
  if (type === 'lock' || type === 'unlock') {
    crmCustomerLockAPI({
      status: type === 'lock' ? '2' : '1', // 1是正常 2 是锁定
      ids: id.value
    }).then(res => {
      ElMessage.message({
        type: 'success',
        message: '操作成功'
      })
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'transform') {
    crmLeadsTransformAPI([id.value]).then(res => {
      ElMessage.message({
        type: 'success',
        message: '转化成功'
      })
      // 刷新待办
      const useCrmStore = useCrmStore();
      useCrmStore.GetMessageNum()
      // this.$store.dispatch('GetMessageNum')

      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'start' || type === 'disable') {
    crmProductStatusAPI({
      ids: [properties.id],
      status: type === 'start' ? '1' : '0'
    }).then(res => {
      ElMessage.message({
        type: 'success',
        message: '操作成功'
      })
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'delete') {
    const request = {
      leads: crmLeadsDeleteAPI,
      customer: detailHeadOption.isSeas ? crmCustomerPoolDeleteAPI : crmCustomerDeleteAPI,
      contacts: crmContactsDeleteAPI,
      business: crmBusinessDeleteAPI,
      contract: crmContractDeleteAPI,
      receivables: crmReceivablesDeleteAPI,
      receivablesPlan: crmReceivablesPlanDeleteAPI,
      visit: crmReturnVisitDeleteAPI,
      product: crmProductDeleteAPI,
      invoice: crmInvoiceDeleteIdsAPI
    }[detailHeadOption.crmType]
    const params = {}
    if (detailHeadOption.isSeas) {
      params.poolId = detailHeadOption.poolId
    }
    params.ids = [parseInt(properties.id)]
    request(detailHeadOption.isSeas ? params : params.ids).then(res => {
      ElMessage.message({
        type: 'success',
        message: '删除成功'
      })
      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'get') {
    // 领取
    crmCustomerReceiveAPI({
      ids: [properties.id],
      poolId: detailHeadOption.poolId
    }).then(res => {
      ElMessage.message({
        type: 'success',
        message: '操作成功'
      })
      // 刷新待办
      const useCrmStore = useCrmStore();
      useCrmStore.GetMessageNum()
      // this.$store.dispatch('GetMessageNum')

      emits('handle', {type: type})
    }).catch(() => {
    })
  } else if (type === 'cancel') {
    crmContractCancelAPI({
      contractId: properties.id
    }).then(res => {
      ElMessage.success('操作成功')
      emits('handle', {type})
    }).catch(() => {
    })
  }
}

function wkIconPre(name) {
  return name.startsWith('wk') ? name : `wk wk-${name}`
}

// 子组件 回调的 结果
function handleCallBack(data) {
  emits('handle', {type: data.type})
}

/** 更多操作 */
/** 获取展示items */
function getSelectionHandleItemsInfo() {
  const handleInfos = {
    transfer: {
      name: '转移',
      type: 'transfer',
      icon: 'transfer'
    },
    transform: {
      name: '转化为客户',
      type: 'transform',
      icon: 'transform'
    },
    export: {
      name: '导出选中',
      type: 'export',
      icon: 'export'
    },
    delete: {
      name: '删除',
      type: 'delete',
      icon: 'delete'
    },
    put_seas: {
      name: '放入公海',
      type: 'put_seas',
      icon: 'seas'
    },
    lock: {
      name: '锁定',
      type: 'lock',
      icon: 'lock'
    },
    unlock: {
      name: '解锁',
      type: 'unlock',
      icon: 'unlock'
    },
    add_user: {
      name: '添加团队成员',
      type: 'add_user',
      icon: 'add'
    },
    delete_user: {
      name: '移除团队成员',
      type: 'delete_user',
      icon: 'remove'
    },
    alloc: {
      name: '分配',
      type: 'alloc',
      icon: 'alloc'
    },
    get: {
      name: '领取',
      type: 'get',
      icon: 'receive'
    },
    start: {
      name: '上架',
      type: 'start',
      icon: 'shelves'
    },
    disable: {
      name: '下架',
      type: 'disable',
      icon: 'sold-out'
    },
    deal_status: {
      name: '更改成交状态',
      type: 'deal_status',
      icon: 's-status'
    },
    cancel: {
      name: '合同作废',
      type: 'cancel',
      icon: 'invalid'
    },
    print: {
      name: '打印',
      type: 'print',
      icon: 'print'
    },
    copyContract: {
      name: '复制合同',
      type: 'copyContract',
      icon: 'icon-double-note'
    }
  }
  if (detailHeadOption.crmType == 'leads') {
    return forSelectionHandleItems(handleInfos, [
      'transform',
      'delete'
    ])
  } else if (detailHeadOption.crmType == 'customer') {
    if (detailHeadOption.isSeas) {
      return forSelectionHandleItems(handleInfos, [
        'delete'
      ])
    } else {
      return forSelectionHandleItems(handleInfos, [
        'transfer',
        'put_seas',
        'lock',
        'unlock',
        'delete'
      ])
    }
  } else if (detailHeadOption.crmType == 'contacts') {
    return forSelectionHandleItems(handleInfos, ['delete'])
  } else if (detailHeadOption.crmType == 'business') {
    return forSelectionHandleItems(handleInfos, ['print', 'delete'])
  } else if (detailHeadOption.crmType == 'contract') {
    return forSelectionHandleItems(handleInfos, ['print', 'delete', 'cancel', 'copyContract'])
  } else if (detailHeadOption.crmType == 'receivables') {
    return forSelectionHandleItems(handleInfos, ['print', 'delete'])
  } else if (detailHeadOption.crmType == 'product') {
    return forSelectionHandleItems(handleInfos, ['delete', 'start', 'disable'])
  } else if (detailHeadOption.crmType == 'visit') {
    return forSelectionHandleItems(handleInfos, [
      'delete'
    ])
  } else if (detailHeadOption.crmType == 'invoice') {
    return forSelectionHandleItems(handleInfos, [
      'delete'
    ])
  } else if (detailHeadOption.crmType == 'receivablesPlan') {
    return forSelectionHandleItems(handleInfos, [
      'delete'
    ])
  }
  return []
}

function forSelectionHandleItems(handleInfos, array) {
  let tempsHandles = []
  for (let index = 0; index < array.length; index++) {
    tempsHandles.push(handleInfos[array[index]])
  }
  return tempsHandles
}

/**
 * 判断是否展示
 */
function whetherTypeShowByPermission(type) {
  console.log("moreTypes", type)
  console.log("moreTypes", crm.value[detailHeadOption.crmType].transfer)
  if (type == 'transfer') {
    return crm.value[detailHeadOption.crmType].transfer
  } else if (type == 'transform') {
    return crm.value[detailHeadOption.crmType].transform
  } else if (type == 'export') {
    if (detailHeadOption.isSeas) {
      if (detailHeadOption.poolId) {
        return detailHeadOption.poolAuth.excelexport
      }
      return crm.value.pool && crm.value.pool.excelexport
    }
    return crm.value[detailHeadOption.crmType].excelexport
  } else if (type == 'delete') {
    if (detailHeadOption.isSeas) {
      if (detailHeadOption.poolId) {
        return detailHeadOption.poolAuth && detailHeadOption.poolAuth.delete
      }
      return crm.value.pool && crm.value.pool.delete && detailHeadOption.poolId
    }
    return crm.value[detailHeadOption.crmType].delete
  } else if (type == 'put_seas') {
    // 放入公海(客户)
    return crm.value[detailHeadOption.crmType].putinpool
  } else if (type == 'lock' || type == 'unlock') {
    // 锁定解锁(客户)
    return crm.value[detailHeadOption.crmType].lock
  } else if (type == 'add_user' || type == 'delete_user') {
    // 添加 移除团队成员
    return crm.value[detailHeadOption.crmType].teamsave
  } else if (type == 'alloc') {
    // 分配(公海)
    if (detailHeadOption.poolId) {
      return detailHeadOption.poolAuth && detailHeadOption.poolAuth.distribute
    }
    return crm.value.pool && crm.value.pool.distribute
  } else if (type == 'get') {
    // 领取(公海)
    if (detailHeadOption.poolId) {
      return detailHeadOption.poolAuth && detailHeadOption.poolAuth.receive
    }
    return crm.value.pool && crm.value.pool.receive && detailHeadOption.poolId
  } else if (type == 'start' || type == 'disable') {
    // 上架 下架(产品)
    return crm.value[detailHeadOption.crmType].status
  } else if (type == 'deal_status') {
    // 客户状态修改
    return crm.value[detailHeadOption.crmType].dealStatus
  } else if (type == 'cancel') {
    // 合同作废 1 通过 10 正常
    if (crm.value[detailHeadOption.crmType].discard && (properties.detail.checkStatus === 1 || properties.detail.checkStatus === 10)) {
      return true
    }
    return false
  } else if (type == 'print') {
    // 打印
    return crm.value[detailHeadOption.crmType].print
  } else if (type == 'copyContract') {
    // 合同复制
    return crm.value[detailHeadOption.crmType].save
  }

  return true
}

/**
 * 上下页切换
 */
function pageChange(type) {
  emits('pageChange', type)
}

</script>

<template>
  <div class="container">
    <flexbox class="t-section" align="stretch">
      <img :src="crmIcon" class="t-section__hd">
      <div class="t-section__bd">
        <div class="type-name">{{ typeName }}</div>
        <flexbox class="type-content">
          <el-tooltip :disabled="!name" :content="name" effect="dark" placement="top-start">
            <div class="name">{{ name }}</div>
          </el-tooltip>
          <slot name="name"></slot>
          <el-button-group v-if="pageList && pageList.length > 1" class="wk-header-page-btn">
            <!--上一个-->
            <el-button icon="el-icon-arrow-left" @click="$emit('pageChange', 'prev')"/>
            <!--下一个-->
            <el-button icon="el-icon-arrow-right" @click="$emit('pageChange', 'next')"/>
          </el-button-group>
        </flexbox>
      </div>
      <div class="t-section__ft">
        <el-button v-if="showTransfer" class="head-handle-button" type="primary"
                   @click="handleTypeClick('transfer')">转移
        </el-button>

        <el-button v-if="showEdit" class="head-handle-button xr-btn--green" type="primary"
                   @click="handleTypeClick('edit')"> 编辑
        </el-button>

        <el-button v-if="showGet" class="head-handle-button" type="primary"
                   @click="handleTypeClick('get')"> 领取
        </el-button>

        <el-button v-if="showAlloc" class="head-handle-button xr-btn--green" type="primary"
                   @click="handleTypeClick('alloc')"> 分配
        </el-button>

        <el-button v-if="showDealStatus" class="head-handle-button" type="primary"
                   @click="handleTypeClick('deal_status')"> 更改成交状态
        </el-button>

        <el-dropdown v-if="permissionMoreTypes && permissionMoreTypes.length > 0"
                     @command="handleTypeClick">
          <template v-slot:default>
            <el-button icon="el-icon-more" class="t-more"/>
          </template>
          <template v-slot:dropdown>
            <el-dropdown-menu>
              <template v-for="(item, index) in permissionMoreTypes" :key="index">
                <el-dropdown-item :command="item.type">
                  {{ item.name }}
                </el-dropdown-item>
              </template>

            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </flexbox>
    <flexbox class="h-section" align="stretch">
      <template v-for="(item, index) in detailHead" :key="index">
        <flexbox-item v-show="item.title" class="h-item" span="200">
          <div class="h-title">{{ item.title }}</div>
          <div class="h-value text-one-line">
            <i v-if="item.showIcon" :style="item.style" :class="item.icon"/>
            {{ item.value }}
          </div>
        </flexbox-item>
      </template>
    </flexbox>
    <!--默认插槽-->
    <slot></slot>

    <TransferHandle :crm-type="detailHeadOption.crmType" :selection-list="[detail]"
                    :dialog-visible="handleDialogShow.transferDialogShow"
                    @handle="handleCallBack"/>
    <AllocHandle :crm-type="detailHeadOption.crmType"
                 :pool-id="detailHeadOption.poolId"
                 :selection-list="[detail]"
                 v-model:dialog-visible="handleDialogShow.allocDialogShow"
                 @handle="handleCallBack"/>
    <DealStatusHandle :value="detail.dealStatus" :crm-type="detailHeadOption.crmType" :selection-list="[detail]"
                      :visible="handleDialogShow.dealStatusShow" @handle="handleCallBack"/>
    <PutPoolHandle :visible="handleDialogShow.putPoolShow" :selection-list="[detail]" @handle="handleCallBack"/>
  </div>
</template>

<style scoped lang="scss">
.wk-header-page-btn {
  flex-shrink: 0;
  margin-left: 8px;

  .el-button + .el-button {
    margin-left: 0 !important;
  }

  .el-button {
    padding: 3px 6px;
    background-color: #F5F7FA;

    i {
      font-weight: bold;
    }
  }

  .el-button:hover, .el-button:focus {
    color: white;
    border-color: #ff6a00;
    background-color: #ff6a00;
  }
}
</style>

<style lang="scss" scoped>
.container {
  position: relative;
  background-color: white;
  border-bottom: 1px solid $xr-border-line-color;
}

.t-section {
  position: relative;
  padding: 30px 20px 5px;
  min-height: 60px;

  &__hd {
    display: block;
    width: 40px;
    height: 40px;
    margin-right: 15px;
  }

  &__bd {
    flex: 1;
    width: 0;

    .type-name {
      color: #999;
      font-size: 12px;
      margin-bottom: 5px;
    }

    .type-content {
      .name {
        color: #333;
        font-size: 16px;
        font-weight: 600;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }
  }

  &__ft {
    flex-shrink: 0;
    margin-left: 20px;
  }

  .t-more {
    margin-left: 15px;
  }

  .t-close {
    display: block;
    width: 40px;
    height: 40px;
    margin-left: 20px;
    padding: 10px;
    cursor: pointer;
  }
}

.h-section {
  position: relative;
  padding: 8px 20px 15px;

  .h-item {
    .h-title {
      font-size: 12px;
      color: #666;
    }

    .h-value {
      min-height: 14px;
      margin-top: 8px;
      font-size: 13px;
      color: #333;
      padding-bottom: 2px;
    }
  }
}

.el-button + .el-button {
  margin-left: 15px;
}

.head-handle-button {
  :deep( i) {
    font-size: 13px;
    margin-right: 5px;
  }
}

@import '/src/styles/iconfont/iconfont.css';
</style>